import * as THREE from './node_modules/three/build/three.module.js';
import { GLTFLoader } from './node_modules/three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from './node_modules/three/examples/jsm/loaders/DRACOLoader.js';
import { OrbitControls } from './node_modules/three/examples/jsm/controls/OrbitControls.js';
//导入高亮对应模块(后处理)
import { RenderPass } from './node_modules/three/examples/jsm/postprocessing/RenderPass.js';
import { OutlinePass } from './node_modules/three/examples/jsm/postprocessing/OutlinePass.js';
import { EffectComposer } from './node_modules/three/examples/jsm/postprocessing/EffectComposer.js';

//object
//当前选中物体
let currentObject = {};

//之前选中的物体
let lastObject = {};
//Canvas
const canvas = document.querySelector('canvas.webgl');
const prDiv = document.querySelector('div.pr');
console.log('canvas===', canvas);

//Scene
const scene = new THREE.Scene();

//简单添加背景
//scene.background=new THREE.Color(0xeeeeee)

//添加天空盒
let urls = [
  './skybox/Sky_RT.jpg', // right
  './skybox/Sky_LF.jpg', // left
  './skybox/Sky_UP.jpg', // top
  './skybox/Sky_DN.jpg', // bottom
  './skybox/Sky_BK.jpg', // back
  './skybox/Sky_FR.jpg', // front
];
let skyboxCubemap = new THREE.CubeTextureLoader().load(urls);
scene.background = skyboxCubemap;

//camera
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight
);
camera.position.z = 5;
scene.add(camera);

//加入光
const light = new THREE.AmbientLight(0xffffff, 1);
camera.add(light);

//render
const renderer = new THREE.WebGLRenderer({
  canvas: canvas,
  antialias: true, //消除锯齿
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputEncoding = THREE.sRGBEncoding; //优化渲染效果

renderer.render(scene, camera);

//使用后处理模块
const composer = new EffectComposer(renderer);
//渲染通道
const renderPass = new RenderPass(scene, camera);
composer.addPass(renderPass);
//高亮边框通道
const outlinePass = new OutlinePass(
  new THREE.Vector2(window.innerWidth, window.innerHeight),
  scene,
  camera
);
outlinePass.edgeStrength = 10;
outlinePass.edgeGlow = 0.1;
outlinePass.edgeThickness = 1;
//outlinePass.pulsePeriod = 2;
outlinePass.visibleEdgeColor.set('#B31985');
outlinePass.hiddenEdgeColor.set('#190a05');
composer.addPass(outlinePass);

let sceneReady = false;
const loadingManager = new THREE.LoadingManager(
  //loaded 载入完成
  () => {
    console.log('载入完成');
    sceneReady = true;
    console.log('scene===', scene);
  },
  //Progress 载入过程

  (itemUrl, itemsLoaded, itemsTotal) => {
    console.log('载入中...', itemsLoaded);
  }
);

//导入模型

const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('./models/draco/');

const gltfLoader = new GLTFLoader(loadingManager);
gltfLoader.setDRACOLoader(dracoLoader);
gltfLoader.load('./models/compressmodel/gsModel.gltf', (gltf) => {
  const object = gltf.scene || gltf.scene[0];

  //1.调整物体位置
  const box = new THREE.Box3().setFromObject(object);
  const size = box.getSize(new THREE.Vector3()).length();
  const center = box.getCenter(new THREE.Vector3());
  object.position.x += object.position.x - center.x;
  object.position.y += object.position.y - center.y;
  object.position.z += object.position.z - center.z;
  //2.调整相机位置
  camera.near = size / 100;
  camera.far = size * 100;
  camera.updateProjectionMatrix();

  camera.position.copy(center);
  camera.position.x += size / 2.0;
  camera.position.y += size / 5.0;
  camera.position.z += size / 2.0;
  camera.lookAt(center);

  scene.add(object);
  console.log('scene===', scene);
});

//让模型动起来
const controls = new OrbitControls(camera, canvas);

//resize 加入大小尺寸的控制
window.addEventListener('resize', () => {
  //更新相机
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  //更新渲染
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});

//使用射线法
const raycaster = new THREE.Raycaster();
//mouse
const mouse = new THREE.Vector2();

window.addEventListener('mousemove', (event) => {
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;

  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
});

const generateTable = (data) => {
  console.log('data===', data);
  var table = document.createElement('table');
  table.className = 'styled-table';
  if (Object.keys(data).length == 0) {
    return;
  }
  var thead = document.createElement('thead');
  var headtr = document.createElement('tr');
  var headFirst = document.createElement('th');
  var headSecond = document.createElement('th');
  headFirst.textContent = '属性';
  headSecond.textContent = '属性值';
  headtr.appendChild(headFirst);
  headtr.appendChild(headSecond);
  thead.appendChild(headtr);
  table.appendChild(thead);

  var tbody = document.createElement('tbody');
  table.appendChild(tbody);

  for (const [key, value] of Object.entries(data)) {
    if (key != 'Properties') {
      var row = document.createElement('tr');
      var cellFirst = document.createElement('td');
      var cellSecond = document.createElement('td');
      cellFirst.textContent = key;
      cellSecond.textContent = value;
      row.appendChild(cellFirst);
      row.appendChild(cellSecond);
      tbody.appendChild(row);
      // table.appendChild(row);
    } else {
      for (const [key, value] of Object.entries(data.Properties)) {
        var row = document.createElement('tr');
        var cellFirst = document.createElement('td');
        var cellSecond = document.createElement('td');
        cellFirst.textContent = key;
        cellSecond.textContent = value;
        row.appendChild(cellFirst);
        row.appendChild(cellSecond);
        tbody.appendChild(row);
        // table.appendChild(row);
      }
    }
  }

  prDiv.innerHTML = '';
  prDiv.style.width = '300px';
  prDiv.style.height = '645px';
  prDiv.appendChild(table);
};

window.addEventListener('click', () => {
  if (
    JSON.stringify(currentObject) != '{}' &&
    currentObject != undefined &&
    currentObject != null &&
    currentObject != lastObject
  ) {
    console.log('选中了');
    console.log('click', currentObject);
    lastObject = currentObject;
    prDiv.style.visibility = 'visible';
    generateTable(currentObject.userData);

    let outlineObjcets = [];
    outlineObjcets.push(currentObject);
    outlinePass.selectedObjects = outlineObjcets;
  } else {
    console.log('没有选中');
    lastObject = {};
    currentObject = {};
    outlinePass.selectedObjects = [];
    prDiv.style.visibility = 'hidden';
  }
});

//animate(动起来)
const animate = function () {
  requestAnimationFrame(animate);
  if (sceneReady) {
    raycaster.setFromCamera(mouse, camera);
    const intersects = raycaster.intersectObjects(
      scene.children[1].children[0].children
    );

    if (intersects.length > 0) {
      const selectedObject = intersects[0].object;
      if (currentObject != selectedObject) {
        currentObject = selectedObject;
      }
    } else {
      currentObject = {};
    }
  }
  //controls 更新
  controls.update();
  renderer.render(scene, camera);
  //composer render
  composer.render();
};

animate();
